/**
 * This script is used to update TextArtefacts.
 * This script sends ajax POST messages to '#' when the submit button is pressed.
 *
 * Depends on:
 *		jquery
 *		setup_ajax.js
 *		ckeditor.js
 */
$(document).ready(function() {

	// Selectors
	var FORM = $('#save-form');
	var FORM_INPUTS = $('FORM :input');
	var ALERTS = $('.alert');
	var SUBMIT_BUTTON = $('#form-save');
	var CANCEL_BUTTON = $('#form-cancel');
	var ALERT_SAVING = $('#saving');
	var ALERT_SUCCESS = $('#save-success');
	var ALERT_ERROR = $('#save-error');

	/* Listeners */	
	SUBMIT_BUTTON.on('click', function() {
		console.log("Clicked submit button.");

		// Reset alerts
		resetAlerts();

		// Show progress bar
		ALERT_SAVING.show();

		// Submits all CKEDITOR data to the TextArea it replaces
		for (instance in CKEDITOR.instances) {
     		CKEDITOR.instances[instance].updateElement();
     	}

     	// Serialize the data in the form
		var serializedData = FORM.serialize();

		// Disable the inputs for the duration of the ajax request
		disableInputs();

		// Post Ajax request
		submitData(serializedData);
	});

	/**
	 *	Submits data
	 */
	function submitData(serializedData) {
		console.log("Submiting data by Ajax...");
		$.ajax({
			type: 'POST',
			url: '#',
			data: serializedData,
			dataType: 'html',
			success: ajaxSuccess,
			error: ajaxError
		});

		console.log("DONE.");
	}

	function ajaxSuccess(response) {
		console.log("Received Ajax Success.");
		resetAlerts();
		enableInputs();
		ALERT_SUCCESS.show();
	}

	function ajaxError(response) {
		console.log("Received Ajax Error.");
		resetAlerts();
		enableInputs();
		ALERT_ERROR.show();
	}

	function resetAlerts() {
		console.log("Resetting alerts.");
		ALERT_SAVING.hide();
		ALERT_ERROR.hide();
		ALERT_SUCCESS.hide();
	}

	function disableInputs() {
		console.log("Disabling inputs.");
		FORM_INPUTS.prop("disabled", true);
		SUBMIT_BUTTON.prop("disabled", true);
		CANCEL_BUTTON.prop("disabled", true);
	}

	function enableInputs() {
		console.log("Enabling inputs.");
		FORM_INPUTS.prop("disabled", false);
		SUBMIT_BUTTON.prop("disabled", false);
		CANCEL_BUTTON.prop("disabled", false);
	}
});